package com.imooc.maokeyang.alllearning.exception;

import com.imooc.maokeyang.alllearning.domain.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常类
 *
 * 重点:
 *
 * implements ResponseBodyAdvice 在springMvc中使用这个
 * 保证 每一个controller不需要返回指定的ResponseResult类型
 *
 * 实现这个接口 对swagger有bug  真tm坑啊
 *
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕捉业务类异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult businessExceptionHandle(BusinessException e) {
        log.error("捕捉到了业务异常:", e);

        return ResponseResult.failure(e.getCode(), e.getMessage());
    }


    /**
     * 拦截运行时异常
     * @param e
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public ResponseResult runtimeExceptionHandle(RuntimeException e) {
        log.error("捕捉到运行时异常:", e);
        return ResponseResult.failure(ErrorCodeEnum.UNKNOWN_ERROR.getCode(), e.getMessage());
    }


    /**
     * 系统级异常
     *
     * @param th
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Throwable.class)
    public ResponseResult throwableHandle(Throwable th) {
        log.error("捕捉到Throwable异常:", th);

        return ResponseResult.failure(ErrorCodeEnum.SYSTEM_ERROR.getCode(), th.getMessage());

    }
}
